package cn.zbmao.web.controller;

import cn.zbmao.web.bean.User;
import cn.zbmao.web.config.TenderConfig;
import cn.zbmao.web.util.CookieUtil;
import cn.zbmao.web.util.DateUtil;
import cn.zbmao.web.util.dao.DaoFactory;
import com.jfinal.aop.ClearInterceptor;
import com.jfinal.aop.ClearLayer;
import com.jfinal.core.Controller;

import javax.servlet.http.Cookie;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class LoginController extends Controller {

	public void index() {
		getSession().removeAttribute("user");
		setAttr("title", "登陆");
        setAttr("param","login");
		setAttr("path", TenderConfig.objectUrl);
		render("/views/account/login.html");
	}

	// 登陆提交
	@ClearInterceptor(ClearLayer.ALL)
	public void loginto() {
		String name = getPara("user_name");
		String pwd = getPara("password");
		String return_url = getPara("return_url");
		int net_auto_login = getParaToInt("net_auto_login",0);
		boolean isUser = DaoFactory.getUserDao().isUser(name, pwd);
		if (isUser) {
			User user = DaoFactory.getUserDao().getUserByName(name);

//判断用户注册的邮箱是否已经通过验证
			if (user.getInt("user_signup_mail") == 1) {
				if (user.getTimestamp("account_matured_time").getTime()>new Date().getTime()) {
					Date date = DateUtil.getNowToDate();
					if (date != null) {
						DaoFactory.getUserDao().updateUserLoginTime(date, user);
					}
					getSession().setAttribute("user", user);
//用户登陆时给用户添加一个登陆cookie
                    String cook= CookieUtil.getCookie(user.getInt("id"), user.getDate("user_login_time"));
                    Cookie cookie=new Cookie("zbmao_id",cook);
                    cookie.setMaxAge(60 * 60 * 24 * 30);
                    cookie.setPath("/");
                    getResponse().addCookie(cookie);

                    DaoFactory.getUserDao().updateCookie(user.getInt("id"),cook);
					if (net_auto_login==1) {						
						setCookie("user_id", user.getInt("id").toString(), 60*60*24*30);
					}

					setAttr("errno",1);
					Map<String, String>map = new HashMap<String,String>();
					map.put("url", return_url);
					setAttr("rsm",map);
					renderJson();
					
				}else{
					setAttr("err", "您的账号已经到期，请联系客服！");
					setAttr("rsm", "null");
					setAttr("errno", -1);
					renderJson();
				}
			} else {
				setAttr("err", "您的账号没有进行邮箱认证！");
				setAttr("rsm", "null");
				setAttr("errno", -1);
				renderJson();
			}
		} else {
			setAttr("err", "用户名或密码不正确");
			setAttr("rsm", "null");
			setAttr("errno", -1);
			setAttr("rsm",new HashMap<String, String>().put("url", return_url));
			renderJson();
		}
	}
//登出
    public void out(){

        getSession().removeAttribute("user");
        Cookie newCookie=new Cookie("zbmao_id",null);
        newCookie.setMaxAge(0);
        newCookie.setPath("/");
        getResponse().addCookie(newCookie);
//        setCookie(newCookie);
        redirect("/login");
    }
}
